<?php
/**
 * Created by PhpStorm.
 * User: rain
 * Date: 2018/4/5
 * Time: 下午4:51
 */

namespace App\Http\Controllers\Api;


use App\Models\Book;
use App\Models\Classify;
use App\Services\UserService;
use App\User;
use App\Utils\ArrayUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class ClassifyController extends AuthorizedController
{
    private $userService;

    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }


    public function selected(Request $request)
    {
        /** @var \App\Models\Users $user */
        $user = $request->apiUser;
        $classifyId = (int)$request->get('classify_id', 0);
        if ($user->classify_id <= 0 && $classifyId > 0){
            $user->classify_id = $classifyId;
            $user->classify_date = date('Y-m-d');
            $user->save();
        }

        return $this->success();
    }

    public function index(Request $request)
    {
        $classifies = Classify::where('is_show', 1)->select(['id', 'name', 'icon', 'description'])->with([
            'books' => function ($query){
                $query->select('*')->orderBy('sort', 'asc');
            }
        ])->orderBy('sort', 'asc')->get()->toArray();

        foreach($classifies as &$classify){
            $books = [];
            foreach($classify['books'] as $book){
                $books[] = [
                    'book_id' => $book['book_id'],
                    'cover' => $book['cover'],
                    'name' => $book['name'],
                ];
            }
            $classify['books'] = $books;
        }

        return $this->success($classifies);
    }


}
